<template>
	<view>
		<js-error mode="bottom" ref="jsError"></js-error>
		<view style="background-color: #FFFFFF;margin-top: 10px;">

			<u-form class="form" ref="uForm" label-position="left">
				<view style="margin-bottom: 20px;font-size: 40rpx;">
					当前打印设备
				</view>
				<u-form-item label="设备名称"  label-width="180">
					{{vuex_print.name || ''}}
				</u-form-item>
				<u-form-item label="设备ID"  label-width="180">
					{{vuex_print.addId || ''}}
				</u-form-item>
			</u-form>

			<view style="text-align: center;margin-top: 300rpx;padding: 10px;" class="flex">
				<button @click="qiehuan()" type="default" class="flex-button">
					切换设备
				</button>
				<button @click="print()" type="primary" class="flex-button">
					打印
				</button>
			</view>

			<view class="canvas-container">
				<!-- canvas  画布根据 filePathArray 图片路径数组加载图片 -->
				<canvas :style="{width: canvasWidth +'px', height: canvasHeight +'px'}" :canvas-id="'firstCanvas'+index"
					:id="'firstCanvas'+index" :class="'firstCanvas'+index" v-for="(item,index) in filePathArray"
					:key="index" />
				<view class="canvas-box">

				</view>
			</view>

		</view>
	</view>

</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				focus: true,
				cbarcode: '',
				printData: '',
				show: {
					setting: false
				},
				deviceList: [],
				canvasWidth: 800,
				canvasHeight: 400,
				filePathArray: [],
				barSizeType: '',
				selIds: '',
				prtQtys: ''
			}
		},
		onLoad(p) {
			// var that = this;
			const data = JSON.parse(p.data)
			this.selIds = data.selIds
			this.prtQtys = data.prtQtys
			console.log(this.selIds, this.prtQtys, 'prtQtys', this.barSizeType)
			// // #ifdef APP-PLUS
			// that.initPrinter();
			// // #endif
			this.getdictData()
		},
		mounted() {
			// var that = this;
			// // #ifdef APP-PLUS
			// that.initPrinter();
			// // #endif
		},
		computed: {
			...mapState(['userInfo']),
		},

		methods: {
			qiehuan() {
				uni.navigateTo({
					url: '/pagesData/user/print',
					events: {
						// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
						Filter(data) {
							console.log(data)
						}
					},
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						//res.eventChannel.emit('initfilter', that.queryData)
					}
				})
			},
			back() {
				uni.navigateBack({
					delta: 2
				})
			},
			getdictData() {
				this.$u.api.dictListData({
					dictType: 'bar_size_type1'
				}).then(res => {
					console.log(res, 'res===')
					this.barSizeType = res[0]['dictValue']
					console.log(res, 'res===', this.barSizeType)
					this.getFilePathArray();
				})
			},
			getFilePathArray() {
				const params = {
					selIds: this.selIds,
					prtQtys: this.prtQtys,
					rsPics: 1,
					barType: this.vuex_config.MoNotify,
					barSizeType: this.barSizeType,
				}
				this.$u.api.mf.printSnNumber(params).then(res => {
					if (res.result == 'true') {
						this.filePathArray = res.pdfUrl
						this.renderCanvas()
					} else {
						this.$refs.jsError.showError('', res.message, 'error');
					}
				})
			},
			renderCanvas() {
				// 根据 filePathArray 图片路径数组加载图片

				let that = this
				console.log(that.filePathArray, 'that.filePathArray===')
				for (let i = 0; i < that.filePathArray.length; i++) {

					let filePath = this.vuex_config.baseUrl + that.filePathArray[i]

					console.log(filePath, 'filePath')

					const firstCanvas = uni.createCanvasContext('firstCanvas' + i, this);
					let scla = 0.78;
					let widthScla = 1
					uni.getImageInfo({
						src: filePath,
						success(res) {
							console.log(res.width + "--" + res.height)
							that.canvasWidth = res.width * scla
							that.canvasHeight = res.height * 0.68
							console.log(res, that.canvasWidth, that.canvasHeight)
							firstCanvas.drawImage(filePath, -50, 0, that.canvasWidth, that.canvasHeight);
							firstCanvas.draw();
							that.$nextTick(() => { //获取画布像素数据

							})
						},
						fail(res) {
							// console.log(res)
							that.$refs.jsError.showError('', res.errMsg, 'error');
						}
					})

				}

			},
			async print() {
				let that = this
				if (!this.vuex_print.addId) {
					that.$refs.jsError.showError('', '请先设置蓝牙打印设备！', 'error');
					return;
				}
				// 循环打印
				const printPromises = this.filePathArray.map((filePath, index) => {
					return new Promise((resolve, reject) => {
						uni.canvasGetImageData({
							canvasId: 'firstCanvas' + index,
							x: 0,
							y: 0,
							width: this.canvasWidth, // 确保这些值在调用前已被正确设置
							height: this.canvasHeight,
							success: (res) => {
								console.log('ImageData success:', res);
								resolve(res); // 将结果解析为 Promise 的值
							},
							fail: (res) => {
								console.error('ImageData fail:', res);
								this.$refs.jsError.showError('', res.errMsg, 'error');
								reject(res.errMsg); // 将错误信息作为 Promise 的拒绝理由
							}
						});
					});
				});

				const imageDatas = await Promise.all(printPromises); // 等待所有图像数据获取完成
				console.log('获取完毕', imageDatas);
				this.printSomething(this.vuex_print, this.printTest, imageDatas);
				// imageDatas.forEach((imageData) => {
				// 	this.printData = imageData; // 根据需要处理打印数据，可能需要进一步调整
				// 	// 假设这是实际的打印函数
				// 	console.log('发送完毕');
				// });

			},
			xuanzhe(item) {
				this.deviceList.forEach(i => {
					if (i.address == item.address) {
						i.check = true
					} else {
						i.check = false
					}
				})
				this.$forceUpdate();
				this.focus = false; // 初始化 第二个输入框focus 属性
				setTimeout(() => {
					this.cbarcode = ''
					this.focus = true; //  第二个输入框获取焦点。
				}, 500)
			},
			confirm() {
				let that = this
				if (this.deviceList.length) {
					let data2 = {}
					this.deviceList.forEach(item => {
						if (item.check) {
							data2 = item
						}
					})
					this.printData = this.cbarcode
					this.focus = false; // 初始化 第二个输入框focus 属性
					setTimeout(() => {
						this.cbarcode = ''
						this.focus = true; //  第二个输入框获取焦点。
					}, 1000)

					uni.request({
						url: this.serverURL_a + `/barcode/decode/checkBarCode`,
						data: {
							barCode: this.printData,
							__sid: this.userInfo.sessionid,
						},
						header: {
							'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
						},
						method: 'POST',
						success: function(data) {
							let res = data.data
							if (res.result == 'true') {
								console.log(this.printData, 'printData===');
								this.printSomething(data2, this.printTest)
							} else {
								console.log('444444===');
								this.$api.msg("请扫描正确的条形码!");
								this.printData = ''
							}
						}.bind(this),
						fail: function() {
							this.$api.msg('无法连接服务，请联系管理');
							this.printData = ''
							return;
						}.bind(this),
					})

				} else {
					this.focus = false; // 初始化 第二个输入框focus 属性
					setTimeout(() => {
						this.cbarcode = ''
						this.focus = true; //  第二个输入框获取焦点。
					}, 1000)
					this.$api.msg("请先配对蓝牙!");
				}

			},
			/** 扫码*/
			showPrinterList: function() {
				var that = this;
				that.show.setting = true;
				for (var i = 0; i < that.deviceList.length; i++) {
					if (that.deviceList[i].name == that.device.name) {
						that.deviceList[i].checked = true
					}
				}
			},
			initPrinter: function() {
				var that = this;
				that.deviceList = [];
				var main = plus.android.runtimeMainActivity();
				var Context = plus.android.importClass("android.content.Context");
				var BManager = main.getSystemService(Context.BLUETOOTH_SERVICE);
				plus.android.importClass(BManager);
				var BAdapter = BManager.getAdapter();
				plus.android.importClass(BAdapter);
				var lists = BAdapter.getBondedDevices();
				plus.android.importClass(lists);
				var iterator = lists.iterator();
				plus.android.importClass(iterator);
				while (iterator.hasNext()) {
					var d = iterator.next();
					plus.android.importClass(d);
					var temp = {
						name: d.getName(),
						address: d.getAddress(),
						status: d.getBondState(),
						uuids: d.getUuids(),
						op: d
					};
					// that.deviceList.push(temp);
					var isPrinterUuid = false;
					if (temp.uuids) {
						for (var i = 0; i < temp.uuids.length; i++) {
							if (temp.uuids[i].toString().toLowerCase() === "00001101-0000-1000-8000-00805f9b34fb") {
								isPrinterUuid = true;
								break;
							}
						}
					}
					if (isPrinterUuid) {
						temp.isPrinter = true;
						that.deviceList.push(temp);
					}
				}
				if (that.deviceList.length) {
					that.deviceList[0].check = true
					this.$forceUpdate();
				}
				this.focus = false; // 初始化 第二个输入框focus 属性
				setTimeout(() => {
					this.cbarcode = ''
					this.focus = true; //  第二个输入框获取焦点。
				}, 500)
				console.log(that.deviceList, 'that.deviceList==');
			},
			printSomething: function(dev, sb, printData) {
				console.log('123')
				var that = this;
				var main = plus.android.runtimeMainActivity();
				var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
				var UUID = plus.android.importClass("java.util.UUID");
				var uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
				var BAdapter = BluetoothAdapter.getDefaultAdapter();
				// var device = BAdapter.getRemoteDevice(dev.address);
				var device = BAdapter.getRemoteDevice(dev.addId);
				plus.android.importClass(device);
				var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
				plus.android.importClass(bluetoothSocket);
				console.log("开始连接打印机:" + dev.name);
				if (!bluetoothSocket.isConnected()) {
					bluetoothSocket.connect();
					if (bluetoothSocket.isConnected()) {
						console.log("设备已连接,开始发送打印文件");
						uni.showToast({
							title: '数据已发送',
						});
						var outputStream = bluetoothSocket.getOutputStream();
						plus.android.importClass(outputStream);
						sb(outputStream, printData);
						bluetoothSocket.close();
						if (!bluetoothSocket.isConnected()) {
							console.log("设备已关闭");
						}
					} else {
						uni.showToast({
							title: '设备连接失败',
							icon: 'error',
							duration: 2000
						});
					}
				}
				this.focus = false;
				setTimeout(() => {
					this.focus = true; //  第二个输入框获取焦点。
				}, 500)
				this.printData = ''
			},
			printTest: function(outputStream, printData) {
				try {
					if (typeof printData === 'string') {
						// 发送文本数据
						console.log(this.printData, 'this.printData==');
						var that = this;
						// 100  70
						// 75  130
						// 30   20
						// var text = "! 0 480 360 378 1\r\n";
						var text = "! 0 320 160 180 1\r\n";
						text += "SPEED 1\r\n"; //打印速度 0 到 5 


						// text += "CENTER\r\n"; //居中 介绍点位置 
						text += `BARCODE 128 1 0 60 0 20 ${that.printData}\r\n`;
						// text += "TEXT 7 0 210 60 HORIZ\r\n";

						// text += "CENTER\r\n"; //居中 介绍点位置
						text += "SETBOLD 0\r\n"; //加粗 1加粗0不加粗
						text += "SETMAG 1 1\r\n"; //放大 宽度 高度  1-16
						text += `T 3 2 40 90 ${that.printData}\r\n`;
						text += "SETMAG 0 0\r\n";
						text += "SETBOLD 0\r\n";


						text += "SETMAG 0 0\r\n";
						text += "SETBOLD 0\r\n";
						text += "FORM\r\n";
						text += "END\r\n";
						text += "PRINT\r\n"
						// console.log(text)
						var arrayBuffer = plus.android.invoke(text, 'getBytes', 'gbk');
						outputStream.write(arrayBuffer);
						outputStream.flush();
					} else if (printData && printData[0]['data']) {
						printData.forEach(item => {
							// var that = this;
							var imageData = item.data;
							var width = item.width;
							var height = item.height;
							// +60
							let strCmd = this.CreatCPCLPage(576, height + 60, 1);
							strCmd += this.addCPCLImageCmd(10, 10, {
								imageData: imageData,
								width: width,
								height: height,
								threshold: 190,
							});
							strCmd += this.addCPCLPrint();
							console.log(strCmd, 'strCmd==');
							var arrayBufferEnd = plus.android.invoke(strCmd, 'getBytes', 'gbk');
							outputStream.write(arrayBufferEnd);
							outputStream.flush();
						})
					} else {
						throw new Error('Unsupported data type');
					}
				} catch (e) {
					console.error('发送数据失败:', e);
				}
			},
			addCPCLPrint: function() {
				var strCmd = 'PRINT\n';
				return strCmd;
			},
			CreatCPCLPage: function(width, height, printNum, rotation = 0, offset = -5) {
				var strCmd = '! ' + offset + ' 200 200 ' + height + ' ' + printNum + '\n';
				strCmd += "PAGE-WIDTH " + width + '\n';
				if (rotation == 1)
					strCmd += "ZPROTATE90\n";
				else if (rotation == 2)
					strCmd += "ZPROTATE180\n";
				else if (rotation == 3)
					strCmd += "ZPROTATE270\n";
				else
					strCmd += "ZPROTATE0\n";
				return strCmd;
			},
			addCPCLImageCmd: function(x, y, data) {
				var strImgCmd = '';
				const threshold = data.threshold || 180;
				let myBitmapWidth = data.width,
					myBitmapHeight = data.height;
				let len = parseInt((myBitmapWidth + 7) / 8); //一行的数据长度
				//console.log('len=',len);
				//console.log('myBitmapWidth=',myBitmapWidth);
				//console.log('myBitmapHeight=',myBitmapHeight);
				let ndata = 0;
				let i = 0;
				let j = 0;
				let sendImageData = new ArrayBuffer(len * myBitmapHeight);
				sendImageData = new Uint8Array(sendImageData);
				let pix = data.imageData;

				for (i = 0; i < myBitmapHeight; i++) {
					for (j = 0; j < len; j++) {
						sendImageData[ndata + j] = 0;
					}
					for (j = 0; j < myBitmapWidth; j++) {
						const grayPixle1 = this.grayPixle(pix.slice((i * myBitmapWidth + j) * 4, (i * myBitmapWidth +
							j) * 4 + 3));
						if (grayPixle1 < threshold)
							sendImageData[ndata + parseInt(j / 8)] |= (0x80 >> (j % 8));

					}
					ndata += len;
				}
				//console.log('sendImageData=',sendImageData);
				//CPCL指令图片数据 
				strImgCmd += 'EG ' + len + ' ' + myBitmapHeight + ' ' + x + ' ' + y + ' ';
				for (i = 0; i < sendImageData.length; i++) {
					strImgCmd += this.Hex2Str(sendImageData[i]);
				}
				strImgCmd += '\n';
				// console.log(strImgCmd);
				return strImgCmd;
			},
			grayPixle: function(pix) {
				return pix[0] * 0.299 + pix[1] * 0.587 + pix[2] * 0.114;
			},
			Hex2Str: function(num) {
				if (num.toString(16).length < 2) return "0" + num.toString(16);
				else
					return num.toString(16);
			},
			printBox: function(p, l, w, k, s) { //起点坐标、长高、宽、线宽、显示(上左下右)
				var text = "";
				if (s.t) {
					text = text.concat("L ", p.x, " ", p.y, " ", w, " ", p.y, " ", k, "\r\n");
				}
				if (s.l) {
					text = text.concat("L ", p.x, " ", p.y, " ", p.x, " ", p.y + l, " ", k, "\r\n");
				}
				if (s.b) {
					text = text.concat("L ", p.x, " ", p.y + l, " ", w, " ", p.y + l, " ", k, "\r\n");
				}
				if (s.r) {
					text = text.concat("L ", w, " ", p.y + l, " ", w, " ", p.y, " ", k, "\r\n");
				}
				return text;
			},
			cutLine: function(p, str) {
				var r = "";
				var max = 18;
				var n = parseInt(str.length / max);
				for (var i = 0; i < n; i++) {
					var temp = str.substr(i * max, max);
					r += "T 3 0 " + p.x + " " + (p.y + 40 * i) + " " + temp + "\r\n"
				}
				var w = str.substr(n * max);
				r += "T 3 0 " + p.x + " " + (p.y + 40 * n) + " " + w + "\r\n";
				return r;
			},
			printLineList: function(p, list) {
				var r = "";
				for (var i = 0; i < list.length && i < 5; i++) {
					r += "T 3 0 " + p.x + " " + (p.y + 40 * i) + " " + list[i] + "\r\n"
				}
				return r;
			},
			printLineList2: function(p, list) {
				var r = "";
				for (var i = 0; i < list.length && i < 10; i = i + 2) {
					r += "T 3 0 " + p.x + " " + (p.y + 60 * i) + " " + list[i] + "\r\n";
					if ((i + 1) < list.length) {
						r += "T 3 0 " + (p.x + 150) + " " + (p.y + 60 * i) + " " + list[i + 1] + "\r\n";
					}
				}
				return r;
			},
			mySleep: async function(time) {
				await this.mypromise(time);
			},
			mypromise: function(time) {
				return new Promise((resolve) => setTimeout(resolve, time));
			}
		}
	}
</script>

<style scoped>
	page {
		padding: 0;
		margin: 0;
	}

	.picked {
		background-color: lavender;
	}

	.canvas-container {
		position: relative;
		width: 100%;
		/* 或具体宽度 */
		height: 100%;
		/* 或具体高度 */
	}

	.canvas-box {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		/* 与canvas宽度一致 */
		height: 100%;
		/* 与canvas高度一致 */
		background-color: #fff;
		/* 半透明黑色背景 rgba(0, 0, 0, 0.5); */
		pointer-events: none;
		/* 允许鼠标事件穿透 */
	}

	.flex-button {
		width: 40%;
	}
</style>